package com.software.practicecenter.service;

import com.software.practicecenter.controller.QuestionController;
import com.software.practicecenter.entity.*;
import com.software.practicecenter.repository.PracticeRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author xiaoliao
 * @Date 2023/5/31 14:39
 */
@Transactional
@Service
public class PracticeRecordService {
    @Autowired
    private PracticeRecordRepository practiceRecordRepository;


    @Autowired
    private QuestionController questionController;

    @Autowired
    private SubPassageService subPassageService;


    public PracticeRecord findById(String id) {
        Optional<PracticeRecord> optional = practiceRecordRepository.findById(id);
        PracticeRecord practiceRecord = null;
        if (optional.isPresent()) {
            practiceRecord = optional.get();
            return practiceRecord;
        }
        else {
            System.out.println("id 不存在");
            return practiceRecord;
        }
    }




    public List<PracticeRecord> findByUserId(String userId){
        List<PracticeRecord> records = practiceRecordRepository.findByUserId(userId);
        return records;
    }

    public List<RecordDTO> findRecords(String userId){

        List<PracticeRecord> practiceRecords = practiceRecordRepository.findByUserId(userId);

//        List<RecordDTO> list =  recordDTOS.stream().sorted(Comparator.comparing(RecordDTO::getDate).reversed()).collect(Collectors.toList());
        List<PracticeRecord> practiceRecordList =  practiceRecords.stream().sorted(Comparator.comparing(PracticeRecord::getDate).reversed()).collect(Collectors.toList());

        List<RecordDTO> recordDTOS = new ArrayList<>();

        for (int i = 0;i< practiceRecordList.size();i++){
            int right = 0;
            double sum = 0;
            RecordDTO recordDTO = new RecordDTO();
            //id
            recordDTO.setId(practiceRecordList.get(i).getId());
            //日期
            String date = practiceRecordList.get(i).getDate();
            String newDate = date.toString().substring(5,10);
            String[] result = newDate.split("-");
            recordDTO.setDate(result[0]+"月"+result[1]+"日");

            //用时
            Integer useTime = practiceRecordList.get(i).getUsedTime();
            recordDTO.setUseTime(useTime + "秒");

            String[] questions = practiceRecordList.get(i).getQuestions().split(",");
            String[] answers = practiceRecordList.get(i).getAnswers().split(",");
            for (int j=0;j< questions.length;j++){
                Question question ;
                question = questionController.findQuestionById(questions[j]);
                if (question.getCorrectOption().equals(answers[j])){
                    right= right+20;
                }else{
                    right+=0;
                }
                Double difficulty_level = question.getDifficultyLevel();
                sum+=difficulty_level;
            }
            //难度
            recordDTO.setDifficultyLevel(sum/5);
            //正确率
            recordDTO.setRight(right+"%");
            SubPassage subPassage = subPassageService.findByNo(practiceRecordList.get(i).getBelongChapter());
            String no = subPassage.getNo();
            String name = subPassage.getName();
            recordDTO.setChapter(no + " " +name);

            recordDTOS.add(recordDTO);

        }

//        List<RecordDTO> list =  recordDTOS.stream().sorted(Comparator.comparing(RecordDTO::getDate).reversed()).collect(Collectors.toList());

        return recordDTOS;


    }

    public void addRecord(PracticeRecord practiceRecord) {
        practiceRecordRepository.save(practiceRecord);
    }

    public com.software.practicecenter.entity.AllRecord findAllByUserId(String userId) {
        com.software.practicecenter.entity.AllRecord allRecord = new com.software.practicecenter.entity.AllRecord();
        List<com.software.practicecenter.entity.PracticeRecord> practiceRecords = practiceRecordRepository.findByUserId(userId);

        //总题目
        allRecord.setPracticeNum(practiceRecords.size()*5+"");

        int num = 0,time=0;
        for (int i = 0;i< practiceRecords.size();i++) {
            time += practiceRecords.get(i).getUsedTime();
            String[] questions = practiceRecords.get(i).getQuestions().split(",");
            String[] answers = practiceRecords.get(i).getAnswers().split(",");
            for (int j=0;j< questions.length;j++){
                Question question ;
                question = questionController.findQuestionById(questions[j]);
                if (question.getCorrectOption().equals(answers[j])){
                    num +=1;
                }else{
                    num+=0;
                }

            }
        }

        DecimalFormat decimalFormat = new DecimalFormat("#0");

        //总正确率
        if (practiceRecords.size()==0){
            allRecord.setAccuracy(0+"%");
        }else {
            double result = (double) num / (practiceRecords.size()*5) *100;
            allRecord.setAccuracy(decimalFormat.format(result)+"%");
            System.out.println(decimalFormat.format(result));
        }


        //总时间
        if (time<60){
            allRecord.setPracticeTime(time+"秒");
        }else {
            double min = (double)time / 60;
            double s = (double) time % 60;
            allRecord.setPracticeTime(decimalFormat.format(min)+"分"+ decimalFormat.format(s) +"秒");
        }

//        allRecord.setPracticeTime(time+"秒");

        return allRecord;

    }
}
